import { getCookie, deleteCookie } from "../js/cookie.js";
import { searchShoppingCarByUser} from "../js/interface.js"


$(async function(){
    var user = getCookie("lgc");
    if(user){
        $(".hide a:first-child").css("display", "none");
        $(".hide a:last-child").css("display", "block");
        $(".hide").eq(0).children().html(`欢迎,${user}`);
        $(".exit").click(function () {
            deleteCookie("lgc");
            location.reload();
        })
    }else{
        location.href = "../html/login.html?returnUrl=" + encodeURIComponent(location.href);
    }

    var result = await searchShoppingCarByUser({ user });
    var { status, msg, list } = result;
    if(status){
        var html = "";
        list.forEach(({ id, goodsName, goodsPrice, goodsImg, num, total }) => {
            var shopprice = (goodsPrice*1).toFixed(2);
            var shoptotal = (total*1).toFixed(2);
            // console.log(id);
            html +=`
                    <li class="goods" data-id="${id}">
                        <label class="checkbox">
                            <input type="checkbox" class="checkOne">
                        </label>
                        <div class="po-area">
                            <div class="time">
                                <label>限时特惠</label>
                                距离活动结束还有
                                <div class="p-time"></div>
                            </div>
                        </div>
                        <div class="pro-main">
                            <a href="javascript:;">
                                <img src="https:${goodsImg}"
                                    alt="">
                            </a>
                            <ul>
                                <li>
                                    <a href="javascript:;">
                                        ${goodsName}
                                    </a>
                                    <div class="p-label">
                                        <span>分期免息</span>
                                    </div>
                                </li>
                                <li>
                                    <div class="p-price">
                                        <span>¥ ${shopprice}</span>
                                    </div>
                                </li>
                                <li>
                                    <div class="p-reduce"><a href="javascript:;">-</a></div>
                                    <div class="p-count"><input type="text" placeholder="1" value="${num}"></div>
                                    <div class="p-add"><a href="javascript:;">+</a></div>
                                </li>
                                <li class="p-total">
                                    <span>¥ ${shoptotal}</span>
                                </li>
                                <li class="del">
                                    <a href="javascript:;">删除</a>
                                </li>
                            </ul>
                        </div>
                    </li>`
        })
        $(".items").html(html);
        // console.log($(".checkOne"));
        //全选控制单选
        $(".checkAll").click(function () {
            var status = $(this).prop("checked");
            $(".checkOne").prop("checked", status);
            $(".checkAll").prop("checked", status);

            settlement();
        });

        //单选控制全选
        // $(".checkOne").click(function () {
        //     var flag = $(".checkOne").is(":not(:checked)");
        //     $(".checkAll").prop("checked", !flag);

        //     settlement();
        // });
        $(document).on("click",".checkOne",function(){
            ifCheck();

            settlement();
        })

        //加
        $(".p-add").click(function(){
            var num = parseInt($(this).prev().children().val());
            num++;
            var user = getCookie("lgc");
            var id = $(this).parents(".goods").attr("data-id");
            $.ajax({
                type: "post",
                url: "../php/changeNumById.php",
                data: { num, id, user },
                dataType: "json",
                success:function(result){
                    console.log(result);
                }
            })
            $(this).prev().children().val(num);

            var oneprice = parseInt($(this).parent().prev().children().children().html().substring(2)).toFixed(2);
            var cost = ((num*oneprice)*1).toFixed(2);
            // console.log(cost);
            $(this).parent().next().html(`<span>¥ ${cost}</span>`);

            settlement()
        })

        //减
        $(".p-reduce").click(async function(){
            var num = parseInt($(this).next().children().val());
            if(num <= 1)return false;
            num--;
            var user = getCookie("lgc");
            var id = $(this).parents(".goods").attr("data-id");
            $.ajax({
                type: "post",
                url: "../php/changeNumById.php",
                data: { num, id, user },
                dataType: "json",
                success:function(result){
                    console.log(result);
                }
            })
            $(this).next().children().val(num);
            
            var oneprice = parseInt($(this).parent().prev().children().children().html().substring(2)).toFixed(2);
            var cost = ((num*oneprice)*1).toFixed(2);
            // console.log(cost);
            $(this).parent().next().html(`<span>¥ ${cost}</span>`);

            settlement();
        })

        //删除
        $(".del").click(function(){
            if(confirm("是否删除该商品")){
                var user = getCookie("lgc");
                var id = $(this).parents(".goods").attr("data-id");
                $.ajax({
                    type: "post",
                    url: "../php/deleteGoods.php",
                    data: { id, user },
                    dataType: "json",
                    success:function(result){
                        console.log(result);
                    }
                });
                $(this).parents(".goods").remove();
            }

            ifCheck();
            settlement();
        })

        //全删
        $(".delAll").click(function(){
            var flag = $(this).prev().children().prop("checked");
            if(flag == true){
                if(confirm("是否删除所有商品")){
                    $(".checkOne").each(function(){
                        var user = getCookie("lgc");
                        var id = $(this).parents(".goods").attr("data-id");
                        console.log(user, id);
                        $.ajax({
                            type: "post",
                            url: "../php/deleteGoods.php",
                            data: { id, user },
                            dataType: "json",
                            success:function(result){
                                console.log(result);
                            }
                        });
                        $(this).parents(".goods").remove();
                    })
                }
            }
            ifCheck();
            settlement();
        })

        // 结算
        //共 件  已选 件    合计  元
        function settlement(){
            var allNum = 0;
            var allPrice = 0;

            $(".checkOne:checked").parents(".goods").each(function(){
                var eachNum = ($(this).find(".p-count").children().val())*1;
                var eachTotal = ($(this).find(".p-total").children().text().substring(2))*1;
                allNum += eachNum;
                allPrice += eachTotal;
            })
            var topr = allPrice.toFixed(2);
            $(".choose").html(`已选择<em>${allNum}</em>件商品`);
            $(".tolp").html(`<label>总计：</label>
            <span>¥&nbsp; ${topr}</span>`)
        }

        //判断全选
        function ifCheck(){
            var flag = $(".checkOne").is(":not(:checked)");
            $(".checkAll").prop("checked",$(".checkOne").length == 0 ?false: !flag);
        }
    }
})


